package com.fsp.streamAPI.streamBasis.mapFilter;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fushengping
 * @className StreamTest
 * @description 测试stream的map和filter过滤方法
 * @date 2021/12/2 16:42
 */
public class StreamTest {
    private static List<Person> list;

    static {
        list = new ArrayList<>();
        list.add(new Person("i", 18, "杭州", 999.9));
        list.add(new Person("am", 19, "温州", 777.7));
        list.add(new Person("iron", 21, "杭州", 888.8));
        list.add(new Person("man", 17, "宁波", 888.8));
    }

    /*测试*/
    public static void main(String[] args) {
        //1.先用stream转化为流的形式
        Stream<Person> stream = list.stream();
        //2.使用filter进行过滤，年龄大于18的
        Stream<Person> personFilter = stream.filter(person -> person.getAge() > 18);
        //3.使用map,只取出name  (map()中可以使用方法引用，filter中无法使用)
        Stream<String> nameStream = personFilter.map(Person::getName);
        System.out.println("\n--------------------------------------\n");
        System.out.println(nameStream);
        //4.使用collect将其转化为list的形式,现在返回值是Stream<String>，没法直接使用,收集成List<String>
        List<String> collect = nameStream.collect(Collectors.toList());
        System.out.println(collect);
        System.out.println("\n--------------------------------------\n");

        /*链式使用*/
        List<String> collect1 = list.stream()
                .filter(person -> person.getAge() <= 18)
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println(collect1);

    }
}
